/*
	The MIT License

	Copyright (c) 2010 IFMO/GameDev Studio

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.
*/

#pragma once

#include "gl_local.h"

#define	VID_WNDCLASSNAME	"GL Display"
#define	VID_WNDNAME			CoreVersion()
#define WS_WINDOW			( WS_CLIPCHILDREN | WS_CLIPSIBLINGS )
#define WS_FULLSCR			( WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_POPUP )
#define WBORDER				( 2*GetSystemMetrics(SM_CXFIXEDFRAME) )
#define HBORDER				( 2*GetSystemMetrics(SM_CYFIXEDFRAME)+GetSystemMetrics(SM_CYCAPTION) )


EGLVidModeDesc_s mode_list[] = {
		//{	640		,	480		,	false	},	//	VGA and MCGA
		//{	800		,	480		,	false	},	//	WGA or WVGA, ASUS Eee PC 700 and 701 series
		{	800		,	600		,	false	},	//	0	SVGA
		{	1024	,	576		,	false	},	//	1	WXGA
		{	1024	,	768		,	false	},	//	2	XGA
		{	1280	,	800		,	false	},	//	3	WXGA
		{	1280	,	960		,	false	},	//	4	SXVGA, Quad VGA
		{	1280	,	1024	,	false	},	//	5	SXGA
		{	1366	,	768		,	false	},	//	6	WXGA
		{	1440	,	900		,	false	},	//	7	WXGA+
		{	1400	,	1050	,	false	},	//	8	SXGA+
		{	1600	,	1024	,	false	},	//	9	WSXGA
		{	1600	,	1200	,	false	},	//	10	UXGA
		{	1680	,	1050	,	false	},	//	11	WSXGA+
		{	1920	,	1200	,	false	},	//	12	WUXGA
		{	1920	,	1400	,	false	},	//	13	TXGA
		{	2048	,	1536	,	false	},	//	14	QXGA
		{	2560	,	1600	,	false	},	//	15	WQXGA
	};
	
const uint MODE_LIST_SIZE	= (sizeof(mode_list) / sizeof(EGLVidModeDesc_s));


//
//	EGLDriver::CheckDisplayModes
//
void EGLDriver::CheckDisplayModes(void)
{
	for (uint i=0; i<MODE_LIST_SIZE; i++)
	{
		DEVMODE	dm;
		memset(&dm, 0, sizeof(dm));
		dm.dmSize		=	sizeof(dm);
		dm.dmPelsWidth	=	mode_list[i].width;
		dm.dmPelsHeight	=	mode_list[i].height;
		dm.dmFields		=	DM_PELSWIDTH | DM_PELSHEIGHT;
		
		int result = ChangeDisplaySettings(&dm, CDS_TEST);
		
		if ( result == DISP_CHANGE_SUCCESSFUL ) {	
			mode_list[i].is_supported	=	true;
		}  else {
			mode_list[i].is_supported	=	false;
		}
	}
}


//
//	EGLDriver::InitDisplay
//
void EGLDriver::InitDisplay(void)
{
	CheckDisplayModes();
	
	CONFIG_REGISTER_VAR(  gl_fullscr		,	false	);
	CONFIG_REGISTER_VAR(  gl_mode			,	0		);
	CONFIG_REGISTER_VAR(  gl_xpos			,	0		);
	CONFIG_REGISTER_VAR(  gl_ypos			,	0		);
	CONFIG_REGISTER_VAR(  gl_stereo			,	false	);
	//CONFIG_REGISTER_VAR(  gl_antialiasing	,	0		);
	
	//
	//	CDS :
	//
_try_again:	
	vid_state.fullscr	=	gl_fullscr->Bool();
	vid_state.mode	=	clamp<uint>(gl_mode->Int(), 0, MODE_LIST_SIZE-1);
	vid_state.h_wnd	=	NULL;

	gl_mode->Set( vid_state.mode );
	
	if (vid_state.fullscr) {
		LOGF("Selected mode : %dx%d FS", mode_list[vid_state.mode].width, mode_list[vid_state.mode].height);
		
		// selected mode is not supported :
		if (!mode_list[vid_state.mode].is_supported) {
			LOGF("Mode is not supported, searching for appropriate mode...");
			
			// try to find good mode :
			uint i;
			for (i=0; i<MODE_LIST_SIZE; i++) {
				if (mode_list[i].is_supported) {
					gl_mode->Set(i);
					goto _try_again;
				}
			}

			// good mode not found (settings should be reseted) :			
			if (i==MODE_LIST_SIZE) {
				LOGF("Appropriate mode not found");
				gl_fullscr->Set(false);
				gl_mode->Set(0);
				goto _try_again;
			}
		}
		
		DEVMODE	dm;
		memset(&dm, 0, sizeof(dm));
		dm.dmSize		=	sizeof(dm);
		dm.dmPelsWidth	=	mode_list[vid_state.mode].width;
		dm.dmPelsHeight	=	mode_list[vid_state.mode].height;
		dm.dmFields		=	DM_PELSWIDTH | DM_PELSHEIGHT;
		
		LOGF("Setting fullscreen mode");
		int result	= ChangeDisplaySettings(&dm, CDS_FULLSCREEN);
		
		if (result!=DISP_CHANGE_SUCCESSFUL) {
			gl_fullscr->Set(false);
			gl_mode->Set(0);
			goto _try_again;
			LOG_WARNING("current display mode is not supported in fullscreen");
			LOG_WARNING("switching to windowed mode");
		} else {
		}
		
	} else 
	{
		LOGF("Selected mode : %dx%d W", mode_list[vid_state.mode].width, mode_list[vid_state.mode].height);
	}
	
	//
	//	Create window :
	//
	//------------------------------------
	//	Register Class :
	WNDCLASSEX	wc;
		memset(&wc, 0, sizeof(WNDCLASSEX));
		wc.cbSize			= sizeof (WNDCLASSEX);
		wc.lpfnWndProc		= (WNDPROC)WndProc;	
		wc.style			= CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
		wc.hInstance		= GetModuleHandle(NULL);
		wc.hbrBackground	= CreateSolidBrush(RGB(0,0,0));
		wc.hCursor			= LoadCursor(NULL, IDC_ARROW);
		wc.lpszClassName	= VID_WNDCLASSNAME;
		wc.hIcon			= 0;//LoadIcon(GetModuleHandle("rend_d3d9.dll"), MAKEINTRESOURCE(IDI_ICON1));
		//	TODO DHG : set icon for created window.
		
	if (!RegisterClassEx(&wc)) {
		FATAL("RegisterClassEx() failed");
	}
		

	//------------------------------------
	//	Create Window :
	int w = mode_list[vid_state.mode].width;
	int h = mode_list[vid_state.mode].height;
	int pos[2];
	pos[0] = gl_xpos->Int();
	pos[1] = gl_ypos->Int();
	
	if (vid_state.fullscr) {
		EString	wndname	= va("%s : OpenGL renderer [FS]", CoreVersion());
		vid_state.h_wnd = CreateWindow(VID_WNDCLASSNAME, wndname.CStr(), WS_FULLSCR, 
							0,0, w,h, 
							NULL, NULL, GetModuleHandle(NULL), 0);
	} else {
		EString	wndname	= va("%s : OpenGL renderer [W]", CoreVersion());
		vid_state.h_wnd = CreateWindow(VID_WNDCLASSNAME, wndname.CStr(), WS_WINDOW, 
							pos[0], pos[1],
							w + WBORDER, h + HBORDER, 
							NULL, NULL, GetModuleHandle(NULL), 0);
	}
							
	if (!vid_state.h_wnd ) { 
		FATAL("CreateWindow() failed");
	}
	
	ShowWindow( vid_state.h_wnd , SW_NORMAL);
	SetForegroundWindow( vid_state.h_wnd );
	SetFocus( vid_state.h_wnd );
	UpdateWindow( vid_state.h_wnd );
}


//
//	EGLDriver::ShutdownDisplay
//
void EGLDriver::ShutdownDisplay(void)
{
	if (!vid_state.fullscr) {
		RECT rect;
		GetWindowRect( vid_state.h_wnd, &rect );
		gl_xpos->Set( rect.left );
		gl_ypos->Set( rect.top );
	}

	if ( vid_state.h_wnd )
		if (!DestroyWindow( vid_state.h_wnd ))
			RUNTIME_ERROR("DestroyWindow() failed");

	if (!UnregisterClass(VID_WNDCLASSNAME, GetModuleHandle(0)))
		RUNTIME_ERROR("UnregisterClass() failed");
		
	if (vid_state.fullscr) {
		ChangeDisplaySettings(NULL, NULL);
	}

}


//
//	EGLDriver::GetScreenSize
//
void EGLDriver::GetScreenSize(uint &w, uint &h)
{
	w	=	mode_list[vid_state.mode].width;
	h	=	mode_list[vid_state.mode].height;
}


//
//	EGLDriver::GetWndDescriptor
//
void *EGLDriver::GetWindowHandle(void)
{
	return (void*)vid_state.h_wnd;
}


//
//	EGLDriver::WndProc
//
LRESULT	EGLDriver::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
	switch( uMsg ) { 
		case WM_MOVE :		break;
		case WM_CREATE :	break;
		case WM_DESTROY :	break;
		case WM_KEYDOWN :	break;
		case WM_CHAR :		break;
		case WM_CLOSE :	 
					PostQuitMessage(0);
					return 0;
				break;
		default :	return DefWindowProc( hWnd, uMsg, wParam, lParam ) ;
	} 
	return DefWindowProc(hWnd, uMsg, wParam, lParam);
}


/*-----------------------------------------------------------------------------
	OpenGL stuff :
-----------------------------------------------------------------------------*/

//
//	EGLDriver::EnumPFDs
//
void EGLDriver::EnumPFDs( void )
{
	PIXELFORMATDESCRIPTOR	pfd;
	
	for (uint i=0; i<1024; i++) {
		int r = DescribePixelFormat( vid_state.h_dc, i, sizeof(PIXELFORMATDESCRIPTOR), &pfd );
		
		if (r==0) {
			continue;
		}
		
		const char *stereo = "";
		
		if ( ( pfd.dwFlags & PFD_SUPPORT_OPENGL	)	== 0 ) continue;
		if ( ( pfd.dwFlags & PFD_DRAW_TO_WINDOW	)	== 0 ) continue;
		if ( ( pfd.dwFlags & PFD_DOUBLEBUFFER	)	== 0 ) continue;
		if ( ( pfd.dwFlags & PFD_TYPE_RGBA		)	== 0 ) continue;
		
		if ( ( pfd.dwFlags & PFD_STEREO			)	!= 0 ) stereo = "stereo";
		
		LOGF(" pfd[%3d] : c=%2d d=%2d s=%2d - %s", i, pfd.cColorBits, pfd.cDepthBits, pfd.cStencilBits, stereo);
	}
}


//
//	EGLDriver::InitGL
//
void EGLDriver::InitGL( void )
{
	if ( ( vid_state.h_dc = GetDC( vid_state.h_wnd ) ) == NULL ) {
		RUNTIME_ERROR( "EGLDriver::InitGL() - GetDC failed\n" );
	}
	
	int	stereo	=	0;
	
	if (gl_stereo->Bool()) {
		LOGF("...stereo is requested");
		stereo	=	PFD_STEREO;
		features[ RS_FEATURE_STEREO ]  = true;
	}
	
	EnumPFDs();

	PIXELFORMATDESCRIPTOR pfd = 
	{
		sizeof(PIXELFORMATDESCRIPTOR),	// size of this pfd
		1,								// version number
		PFD_DRAW_TO_WINDOW |			// support window
		stereo	|						// support stereo
		PFD_SUPPORT_OPENGL |			// support OpenGL
		PFD_DOUBLEBUFFER,				// double buffered
		PFD_TYPE_RGBA,					// RGBA type
		32,								// ** 32-bit color depth **
		0, 0, 0, 0, 0, 0,				// color bits ignored
		0,								// no alpha buffer
		0,								// shift bit ignored
		0,								// no accumulation buffer
		0, 0, 0, 0, 					// accum bits ignored
		24,								// ** 24-bit z-buffer ** 
		8,								// ** 8-bit stencil buffer **
		0,								// no auxiliary buffer
		PFD_MAIN_PLANE,					// main layer
		0,								// reserved
		0, 0, 0							// layer masks ignored
    };

    int pixel_format;

	if ( ( pixel_format = ChoosePixelFormat(vid_state.h_dc, &pfd)) == 0 ) {
		RUNTIME_ERROR("EGLDriver::InitGL() - ChoosePixelFormat failed\n");
	}
	
	if ( SetPixelFormat(vid_state.h_dc, pixel_format, &pfd) == FALSE ) {
		RUNTIME_ERROR("EGLDriver::InitGL() - SetPixelFormat failed\n");
	}

	if ( DescribePixelFormat( vid_state.h_dc, pixel_format, sizeof(PIXELFORMATDESCRIPTOR), &pfd) == 0 ) {
		RUNTIME_ERROR("EGLDriver::InitGL() - DescribePixelFormat failed\n");
	}

	LOGF("...selected pfd : c=%d d=%d s=%d", pfd.cColorBits, pfd.cDepthBits, pfd.cStencilBits);
	
	if (pfd.dwFlags & PFD_STEREO) {
		LOGF("...stereo is enabled");
		features[ RS_FEATURE_STEREO ]  = true;
	} else {
		LOGF("...stereo is disabled");
		features[ RS_FEATURE_STEREO ]  = false;
	}
	

	if ( ( vid_state.h_gl_rend_context = wglCreateContext( vid_state.h_dc ) ) == 0 ) {
		RUNTIME_ERROR( "EGLDriver::InitGL() - wglCreateContext failed\n" );
	}

	wglMakeCurrent(vid_state.h_dc, vid_state.h_gl_rend_context);
	
	
	InitGLExtensions();
}

//
//	EGLDriver::ShutdownGL
//
void EGLDriver::ShutdownGL( void )
{
	wglMakeCurrent(vid_state.h_dc, NULL);			//deselect rendering context
	wglDeleteContext(vid_state.h_gl_rend_context);	//delete rendering context
}


/*-----------------------------------------------------------------------------
	GL EXTENSIONS :
-----------------------------------------------------------------------------*/

void EGLDriver::CheckGLExtension(const char *extname) 
{
	if (glewIsSupported(extname)) {						
		LOGF("Supported : %s", extname);
	} else {											
		LOG_ERROR("%s is not supported", extname);		
		RUNTIME_ERROR(va("%s is not supported", extname));	
	}
}		


//
//	EGLDriver::InitGLExtensions
//
void EGLDriver::InitGLExtensions( void )
{
	glewInit();
	
	LOGF("GL_VENDOR     : %s", glGetString( GL_VENDOR     ));
	LOGF("GL_RENDERER   : %s", glGetString( GL_RENDERER   ));
	LOGF("GL_VERSION    : %s", glGetString( GL_VERSION    ));

	LOGF("GL_EXTENSIONS :");
	
	EString	extensions	=	(const char*)glGetString( GL_EXTENSIONS );
	uint n0 = 0;
	while (true) {
		uint n1 = extensions.Find(' ', n0, EString::NPOS);
		
		if (n1==EString::NPOS) {
			break;
		}
		
		EString	ext = extensions.Substr(n0, n1);
		n0 = n1+1;
		
		//LOGF("  %s", ext.CStr());
	}
	
	CheckGLExtension( "GL_VERSION_2_0"	);

	
	//GLint cube_tex_size = 0;
	//glGetIntegerv(GL_MAX_3D_TEXTURE_SIZE, &cube_tex_size);	
	//LOGF("GL_MAX_3D_TEXTURE_SIZE = %d", cube_tex_size);
	//GLCheckExtension( "GL_"
}